<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 4.2.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/myblogs/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/myblogs/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/myblogs/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/myblogs/images/logo.svg" color="#222">

<link rel="stylesheet" href="/myblogs/css/main.css">


<link rel="stylesheet" href="/myblogs/lib/font-awesome/css/font-awesome.min.css">
  <link rel="stylesheet" href="/myblogs/lib/pace/pace-theme-minimal.min.css">
  <script src="/myblogs/lib/pace/pace.min.js"></script>


<script id="hexo-configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    hostname: new URL('http://hackmgod.gitee.io').hostname,
    root: '/myblogs/',
    scheme: 'Gemini',
    version: '7.7.0',
    exturl: false,
    sidebar: {"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},
    copycode: {"enable":false,"show_result":false,"style":null},
    back2top: {"enable":true,"sidebar":false,"scrollpercent":false},
    bookmark: {"enable":false,"color":"#222","save":"auto"},
    fancybox: false,
    mediumzoom: false,
    lazyload: false,
    pangu: false,
    comments: {"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},
    algolia: {
      appID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    },
    localsearch: {"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},
    path: 'search.xml',
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}}
  };
</script>

  <meta name="description" content="状态模式（详解版）">
<meta property="og:type" content="article">
<meta property="og:title" content="【30】状态模式（详解版）">
<meta property="og:url" content="http://hackmgod.gitee.io/2020/01/17/%E3%80%9030%E3%80%91%E7%8A%B6%E6%80%81%E6%A8%A1%E5%BC%8F%EF%BC%88%E8%AF%A6%E8%A7%A3%E7%89%88%EF%BC%89/index.html">
<meta property="og:site_name" content="H.m博客">
<meta property="og:description" content="状态模式（详解版）">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="http://c.biancheng.net/uploads/allimg/181116/3-1Q11615412U55.gif">
<meta property="og:image" content="http://c.biancheng.net/uploads/allimg/181116/3-1Q11615425V39.gif">
<meta property="og:image" content="http://c.biancheng.net/uploads/allimg/181116/3-1Q116154332451.gif">
<meta property="og:image" content="http://c.biancheng.net/uploads/allimg/181116/3-1Q116154432352.gif">
<meta property="og:image" content="http://c.biancheng.net/uploads/allimg/181116/3-1Q116154539147.gif">
<meta property="article:published_time" content="2020-01-17T05:59:17.000Z">
<meta property="article:modified_time" content="2020-01-17T10:10:20.025Z">
<meta property="article:author" content="H.m">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http://c.biancheng.net/uploads/allimg/181116/3-1Q11615412U55.gif">

<link rel="canonical" href="http://hackmgod.gitee.io/2020/01/17/%E3%80%9030%E3%80%91%E7%8A%B6%E6%80%81%E6%A8%A1%E5%BC%8F%EF%BC%88%E8%AF%A6%E8%A7%A3%E7%89%88%EF%BC%89/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome: false,
    isPost: true
  };
</script>

  <title>【30】状态模式（详解版） | H.m博客</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

<link rel="alternate" href="/myblogs/atom.xml" title="H.m博客" type="application/atom+xml">
</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-meta">

    <div>
      <a href="/myblogs/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">H.m博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
        <p class="site-subtitle">www.hackm.cn</p>
  </div>

  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>
</div>


<nav class="site-nav">
  
  <ul id="menu" class="menu">
        <li class="menu-item menu-item-home">

    <a href="/myblogs/" rel="section"><i class="fa fa-fw fa-home"></i>首页</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/myblogs/categories/" rel="section"><i class="fa fa-fw fa-th"></i>分类</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/myblogs/archives/" rel="section"><i class="fa fa-fw fa-archive"></i>归档</a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>

</nav>
  <div class="site-search">
    <div class="popup search-popup">
    <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocorrect="off" autocapitalize="none"
           placeholder="搜索..." spellcheck="false"
           type="text" id="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result"></div>

</div>
<div class="search-pop-overlay"></div>

  </div>
</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content">
            

  <div class="posts-expand">
      
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block " lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://hackmgod.gitee.io/2020/01/17/%E3%80%9030%E3%80%91%E7%8A%B6%E6%80%81%E6%A8%A1%E5%BC%8F%EF%BC%88%E8%AF%A6%E8%A7%A3%E7%89%88%EF%BC%89/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="http://img.hao661.com/zt.hao661.com/uploads/allimg/141006/0644042451-0.jpg">
      <meta itemprop="name" content="H.m">
      <meta itemprop="description" content="欢迎您的到来！">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="H.m博客">
    </span>
      <header class="post-header">
		
        <h1 class="post-title" itemprop="name headline">
          【30】状态模式（详解版）
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>
              

              <time title="创建时间：2020-01-17 13:59:17 / 修改时间：18:10:20" itemprop="dateCreated datePublished" datetime="2020-01-17T13:59:17+08:00">2020-01-17</time>
            </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/myblogs/categories/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F/" itemprop="url" rel="index">
                    <span itemprop="name">设计模式</span>
                  </a>
                </span>
            </span>

          
            <div class="post-description">状态模式（详解版）</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h2 id="【30】状态模式（详解版）"><a href="#【30】状态模式（详解版）" class="headerlink" title="【30】状态模式（详解版）"></a>【30】状态模式（详解版）</h2><p>在软件开发过程中，应用程序中的有些对象可能会根据不同的情况做出不同的行为，我们把这种对象称为有状态的对象，而把影响对象行为的一个或多个动态变化的属性称为状态。当有状态的对象与外部事件产生互动时，其内部状态会发生改变，从而使得其行为也随之发生改变。如人的情绪有高兴的时候和伤心的时候，不同的情绪有不同的行为，当然外界也会影响其情绪变化。</p>
<p>对这种有状态的对象编程，传统的解决方案是：将这些所有可能发生的情况全都考虑到，然后使用 if-else 语句来做状态判断，再进行不同情况的处理。但当对象的状态很多时，程序会变得很复杂。而且增加新的状态要添加新的 if-else 语句，这违背了“开闭原则”，不利于程序的扩展。</p>
<p>以上问题如果采用“状态模式”就能很好地得到解决。状态模式的解决思想是：当控制一个对象状态转换的条件表达式过于复杂时，把相关“判断逻辑”提取出来，放到一系列的状态类当中，这样可以把原来复杂的逻辑判断简单化。</p>
<h2 id="状态模式的定义与特点"><a href="#状态模式的定义与特点" class="headerlink" title="状态模式的定义与特点"></a>状态模式的定义与特点</h2><p>状态（State）模式的定义：对有状态的对象，把复杂的“判断逻辑”提取到不同的状态对象中，允许状态对象在其内部状态发生改变时改变其行为。</p>
<p>状态模式是一种对象行为型模式，其主要优点如下。</p>
<ol>
<li>状态模式将与特定状态相关的行为局部化到一个状态中，并且将不同状态的行为分割开来，满足“单一职责原则”。</li>
<li>减少对象间的相互依赖。将不同的状态引入独立的对象中会使得状态转换变得更加明确，且减少对象间的相互依赖。</li>
<li>有利于程序的扩展。通过定义新的子类很容易地增加新的状态和转换。</li>
</ol>
<p>状态模式的主要缺点如下。</p>
<ol>
<li>状态模式的使用必然会增加系统的类与对象的个数。</li>
<li>状态模式的结构与实现都较为复杂，如果使用不当会导致程序结构和代码的混乱。<h2 id="状态模式的结构与实现"><a href="#状态模式的结构与实现" class="headerlink" title="状态模式的结构与实现"></a>状态模式的结构与实现</h2>状态模式把受环境改变的对象行为包装在不同的状态对象里，其意图是让一个对象在其内部状态改变的时候，其行为也随之改变。现在我们来分析其基本结构和实现方法。<h4 id="1-模式的结构"><a href="#1-模式的结构" class="headerlink" title="1. 模式的结构"></a>1. 模式的结构</h4>状态模式包含以下主要角色。</li>
<li>环境（Context）角色：也称为上下文，它定义了客户感兴趣的接口，维护一个当前状态，并将与状态相关的操作委托给当前状态对象来处理。</li>
<li>抽象状态（State）角色：定义一个接口，用以封装环境对象中的特定状态所对应的行为。</li>
<li>具体状态（Concrete    State）角色：实现抽象状态所对应的行为。</li>
</ol>
<p>其结构图如图 1 所示。<br><img src="http://c.biancheng.net/uploads/allimg/181116/3-1Q11615412U55.gif" alt="状态模式的结构图"><br>图1 状态模式的结构图</p>
<h4 id="2-模式的实现"><a href="#2-模式的实现" class="headerlink" title="2. 模式的实现"></a>2. 模式的实现</h4><p>状态模式的实现代码如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br></pre></td><td class="code"><pre><span class="line">package state;</span><br><span class="line">public class StatePatternClient</span><br><span class="line">&#123;</span><br><span class="line">    public static void main(String[] args)</span><br><span class="line">    &#123;       </span><br><span class="line">        Context context&#x3D;new Context();    &#x2F;&#x2F;创建环境       </span><br><span class="line">        context.Handle();    &#x2F;&#x2F;处理请求</span><br><span class="line">        context.Handle();</span><br><span class="line">        context.Handle();</span><br><span class="line">        context.Handle();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line">&#x2F;&#x2F;环境类</span><br><span class="line">class Context</span><br><span class="line">&#123;</span><br><span class="line">    private State state;</span><br><span class="line">    &#x2F;&#x2F;定义环境类的初始状态</span><br><span class="line">    public Context()</span><br><span class="line">    &#123;</span><br><span class="line">        this.state&#x3D;new ConcreteStateA();</span><br><span class="line">    &#125;</span><br><span class="line">    &#x2F;&#x2F;设置新状态</span><br><span class="line">    public void setState(State state)</span><br><span class="line">    &#123;</span><br><span class="line">        this.state&#x3D;state;</span><br><span class="line">    &#125;</span><br><span class="line">    &#x2F;&#x2F;读取状态</span><br><span class="line">    public State getState()</span><br><span class="line">    &#123;</span><br><span class="line">        return(state);</span><br><span class="line">    &#125;</span><br><span class="line">    &#x2F;&#x2F;对请求做处理</span><br><span class="line">    public void Handle()</span><br><span class="line">    &#123;</span><br><span class="line">        state.Handle(this);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line">&#x2F;&#x2F;抽象状态类</span><br><span class="line">abstract class State</span><br><span class="line">&#123;</span><br><span class="line">    public abstract void Handle(Context context);</span><br><span class="line">&#125;</span><br><span class="line">&#x2F;&#x2F;具体状态A类</span><br><span class="line">class ConcreteStateA extends State</span><br><span class="line">&#123;</span><br><span class="line">    public void Handle(Context context)</span><br><span class="line">    &#123;</span><br><span class="line">        System.out.println(&quot;当前状态是 A.&quot;);</span><br><span class="line">        context.setState(new ConcreteStateB());</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line">&#x2F;&#x2F;具体状态B类</span><br><span class="line">class ConcreteStateB extends State</span><br><span class="line">&#123;</span><br><span class="line">    public void Handle(Context context)</span><br><span class="line">    &#123;</span><br><span class="line">        System.out.println(&quot;当前状态是 B.&quot;);</span><br><span class="line">        context.setState(new ConcreteStateA());</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>


<p>程序运行结果如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">当前状态是 A.</span><br><span class="line">当前状态是 B.</span><br><span class="line">当前状态是 A.</span><br><span class="line">当前状态是 B.</span><br></pre></td></tr></table></figure>

<h2 id="状态模式的应用实例"><a href="#状态模式的应用实例" class="headerlink" title="状态模式的应用实例"></a>状态模式的应用实例</h2><p>【例1】用“状态模式”设计一个学生成绩的状态转换程序。</p>
<p>分析：本实例包含了“不及格”“中等”和“优秀” 3 种状态，当学生的分数小于 60 分时为“不及格”状态，当分数大于等于 60 分且小于 90 分时为“中等”状态，当分数大于等于 90 分时为“优秀”状态，我们用状态模式来实现这个程序。</p>
<p>首先，定义一个抽象状态类（AbstractState），其中包含了环境属性、状态名属性和当前分数属性，以及加减分方法 addScore(intx) 和检查当前状态的抽象方法 checkState()；然后，定义“不及格”状态类 LowState、“中等”状态类 MiddleState 和“优秀”状态类 HighState，它们是具体状态类，实现 checkState() 方法，负责检査自己的状态，并根据情况转换；最后，定义环境类（ScoreContext），其中包含了当前状态对象和加减分的方法 add(int score)，客户类通过该方法来改变成绩状态。图 2 所示是其结构图。</p>
<p><img src="http://c.biancheng.net/uploads/allimg/181116/3-1Q11615425V39.gif" alt="学生成绩的状态转换程序的结构图"><br>图2 学生成绩的状态转换程序的结构图</p>
<p>程序代码如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br></pre></td><td class="code"><pre><span class="line">package state;</span><br><span class="line">public class ScoreStateTest</span><br><span class="line">&#123;</span><br><span class="line">    public static void main(String[] args)</span><br><span class="line">    &#123;</span><br><span class="line">        ScoreContext account&#x3D;new ScoreContext();</span><br><span class="line">        System.out.println(&quot;学生成绩状态测试：&quot;);</span><br><span class="line">        account.add(30);</span><br><span class="line">        account.add(40);</span><br><span class="line">        account.add(25);</span><br><span class="line">        account.add(-15);</span><br><span class="line">        account.add(-25);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line">&#x2F;&#x2F;环境类</span><br><span class="line">class ScoreContext</span><br><span class="line">&#123;</span><br><span class="line">    private AbstractState state;</span><br><span class="line">    ScoreContext()</span><br><span class="line">    &#123;</span><br><span class="line">        state&#x3D;new LowState(this);</span><br><span class="line">    &#125;</span><br><span class="line">    public void setState(AbstractState state)</span><br><span class="line">    &#123;</span><br><span class="line">        this.state&#x3D;state;</span><br><span class="line">    &#125;</span><br><span class="line">    public AbstractState getState()</span><br><span class="line">    &#123;</span><br><span class="line">        return state;</span><br><span class="line">    &#125;   </span><br><span class="line">    public void add(int score)</span><br><span class="line">    &#123;</span><br><span class="line">        state.addScore(score);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line">&#x2F;&#x2F;抽象状态类</span><br><span class="line">abstract class AbstractState</span><br><span class="line">&#123;</span><br><span class="line">    protected ScoreContext hj;  &#x2F;&#x2F;环境</span><br><span class="line">    protected String stateName; &#x2F;&#x2F;状态名</span><br><span class="line">    protected int score; &#x2F;&#x2F;分数</span><br><span class="line">    public abstract void checkState(); &#x2F;&#x2F;检查当前状态</span><br><span class="line">    public void addScore(int x)</span><br><span class="line">    &#123;</span><br><span class="line">        score+&#x3D;x;       </span><br><span class="line">        System.out.print(&quot;加上：&quot;+x+&quot;分，\t当前分数：&quot;+score );</span><br><span class="line">        checkState();</span><br><span class="line">        System.out.println(&quot;分，\t当前状态：&quot;+hj.getState().stateName);</span><br><span class="line">    &#125;   </span><br><span class="line">&#125;</span><br><span class="line">&#x2F;&#x2F;具体状态类：不及格</span><br><span class="line">class LowState extends AbstractState</span><br><span class="line">&#123;</span><br><span class="line">    public LowState(ScoreContext h)</span><br><span class="line">    &#123;</span><br><span class="line">        hj&#x3D;h;</span><br><span class="line">        stateName&#x3D;&quot;不及格&quot;;</span><br><span class="line">        score&#x3D;0;</span><br><span class="line">    &#125;</span><br><span class="line">    public LowState(AbstractState state)</span><br><span class="line">    &#123;</span><br><span class="line">        hj&#x3D;state.hj;</span><br><span class="line">        stateName&#x3D;&quot;不及格&quot;;</span><br><span class="line">        score&#x3D;state.score;</span><br><span class="line">    &#125;</span><br><span class="line">    public void checkState()</span><br><span class="line">    &#123;</span><br><span class="line">        if(score&gt;&#x3D;90)</span><br><span class="line">        &#123;</span><br><span class="line">            hj.setState(new HighState(this));</span><br><span class="line">        &#125;</span><br><span class="line">        else if(score&gt;&#x3D;60)</span><br><span class="line">        &#123;</span><br><span class="line">            hj.setState(new MiddleState(this));</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;   </span><br><span class="line">&#125;</span><br><span class="line">&#x2F;&#x2F;具体状态类：中等</span><br><span class="line">class MiddleState extends AbstractState</span><br><span class="line">&#123;</span><br><span class="line">    public MiddleState(AbstractState state)</span><br><span class="line">    &#123;</span><br><span class="line">        hj&#x3D;state.hj;</span><br><span class="line">        stateName&#x3D;&quot;中等&quot;;</span><br><span class="line">        score&#x3D;state.score;</span><br><span class="line">    &#125;</span><br><span class="line">    public void checkState()</span><br><span class="line">    &#123;</span><br><span class="line">        if(score&lt;60)</span><br><span class="line">        &#123;</span><br><span class="line">            hj.setState(new LowState(this));</span><br><span class="line">        &#125;</span><br><span class="line">        else if(score&gt;&#x3D;90)</span><br><span class="line">        &#123;</span><br><span class="line">            hj.setState(new HighState(this));</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line">&#x2F;&#x2F;具体状态类：优秀</span><br><span class="line">class HighState extends AbstractState</span><br><span class="line">&#123;</span><br><span class="line">    public HighState(AbstractState state)</span><br><span class="line">    &#123;</span><br><span class="line">        hj&#x3D;state.hj;</span><br><span class="line">        stateName&#x3D;&quot;优秀&quot;;</span><br><span class="line">        score&#x3D;state.score;</span><br><span class="line">    &#125;           </span><br><span class="line">    public void checkState()</span><br><span class="line">    &#123;</span><br><span class="line">        if(score&lt;60)</span><br><span class="line">        &#123;</span><br><span class="line">            hj.setState(new LowState(this));</span><br><span class="line">        &#125;</span><br><span class="line">        else if(score&lt;90)</span><br><span class="line">        &#123;</span><br><span class="line">            hj.setState(new MiddleState(this));</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>


<p>程序运行结果如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">学生成绩状态测试：</span><br><span class="line">加上：30分，    当前分数：30分，    当前状态：不及格</span><br><span class="line">加上：40分，    当前分数：70分，    当前状态：中等</span><br><span class="line">加上：25分，    当前分数：95分，    当前状态：优秀</span><br><span class="line">加上：-15分，    当前分数：80分，    当前状态：中等</span><br><span class="line">加上：-25分，    当前分数：55分，    当前状态：不及格</span><br></pre></td></tr></table></figure>


<p>【例2】用“状态模式”设计一个多线程的状态转换程序。</p>
<p>分析：多线程存在 5 种状态，分别为新建状态、就绪状态、运行状态、阻塞状态和死亡状态，各个状态当遇到相关方法调用或事件触发时会转换到其他状态，其状态转换规律如图 3 所示。</p>
<p><img src="http://c.biancheng.net/uploads/allimg/181116/3-1Q116154332451.gif" alt="线程状态转换图"><br>图3 线程状态转换图</p>
<p>现在先定义一个抽象状态类（TheadState），然后为图 3 所示的每个状态设计一个具体状态类，它们是新建状态（New）、就绪状态（Runnable ）、运行状态（Running）、阻塞状态（Blocked）和死亡状态（Dead），每个状态中有触发它们转变状态的方法，环境类（ThreadContext）中先生成一个初始状态（New），并提供相关触发方法，图 4 所示是线程状态转换程序的结构图。</p>
<p><img src="http://c.biancheng.net/uploads/allimg/181116/3-1Q116154432352.gif" alt="线程状态转换程序的结构图"><br>图4 线程状态转换程序的结构图</p>
<p>程序代码如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br><span class="line">158</span><br><span class="line">159</span><br><span class="line">160</span><br><span class="line">161</span><br></pre></td><td class="code"><pre><span class="line">package state;</span><br><span class="line">public class ThreadStateTest</span><br><span class="line">&#123;</span><br><span class="line">    public static void main(String[] args)</span><br><span class="line">    &#123;</span><br><span class="line">        ThreadContext context&#x3D;new ThreadContext();</span><br><span class="line">        context.start();</span><br><span class="line">        context.getCPU();</span><br><span class="line">        context.suspend();</span><br><span class="line">        context.resume();</span><br><span class="line">        context.getCPU();</span><br><span class="line">        context.stop();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line">&#x2F;&#x2F;环境类</span><br><span class="line">class ThreadContext</span><br><span class="line">&#123;</span><br><span class="line">    private ThreadState state;</span><br><span class="line">    ThreadContext()</span><br><span class="line">    &#123;</span><br><span class="line">        state&#x3D;new New();</span><br><span class="line">    &#125;</span><br><span class="line">    public void setState(ThreadState state)</span><br><span class="line">    &#123;</span><br><span class="line">        this.state&#x3D;state;</span><br><span class="line">    &#125;</span><br><span class="line">    public ThreadState getState()</span><br><span class="line">    &#123;</span><br><span class="line">        return state;</span><br><span class="line">    &#125;   </span><br><span class="line">    public void start()</span><br><span class="line">    &#123;</span><br><span class="line">        ((New) state).start(this);</span><br><span class="line">    &#125;</span><br><span class="line">    public void getCPU()</span><br><span class="line">    &#123;</span><br><span class="line">        ((Runnable) state).getCPU(this);</span><br><span class="line">    &#125;</span><br><span class="line">    public void suspend()</span><br><span class="line">    &#123;</span><br><span class="line">        ((Running) state).suspend(this);</span><br><span class="line">    &#125;</span><br><span class="line">    public void stop()</span><br><span class="line">    &#123;</span><br><span class="line">        ((Running) state).stop(this);</span><br><span class="line">    &#125;</span><br><span class="line">    public void resume()</span><br><span class="line">    &#123;</span><br><span class="line">        ((Blocked) state).resume(this);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line">&#x2F;&#x2F;抽象状态类：线程状态</span><br><span class="line">abstract class ThreadState</span><br><span class="line">&#123;</span><br><span class="line">    protected String stateName; &#x2F;&#x2F;状态名</span><br><span class="line">&#125;</span><br><span class="line">&#x2F;&#x2F;具体状态类：新建状态</span><br><span class="line">class New extends ThreadState</span><br><span class="line">&#123;</span><br><span class="line">    public New()</span><br><span class="line">    &#123;       </span><br><span class="line">        stateName&#x3D;&quot;新建状态&quot;;</span><br><span class="line">        System.out.println(&quot;当前线程处于：新建状态.&quot;);   </span><br><span class="line">    &#125;</span><br><span class="line">    public void start(ThreadContext hj)</span><br><span class="line">    &#123;</span><br><span class="line">        System.out.print(&quot;调用start()方法--&gt;&quot;);</span><br><span class="line">        if(stateName.equals(&quot;新建状态&quot;))</span><br><span class="line">        &#123;</span><br><span class="line">            hj.setState(new Runnable());</span><br><span class="line">        &#125;</span><br><span class="line">        else</span><br><span class="line">        &#123;</span><br><span class="line">            System.out.println(&quot;当前线程不是新建状态，不能调用start()方法.&quot;);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;   </span><br><span class="line">&#125;</span><br><span class="line">&#x2F;&#x2F;具体状态类：就绪状态</span><br><span class="line">class Runnable extends ThreadState</span><br><span class="line">&#123;</span><br><span class="line">    public Runnable()</span><br><span class="line">    &#123;       </span><br><span class="line">        stateName&#x3D;&quot;就绪状态&quot;;</span><br><span class="line">        System.out.println(&quot;当前线程处于：就绪状态.&quot;);   </span><br><span class="line">    &#125;</span><br><span class="line">    public void getCPU(ThreadContext hj)</span><br><span class="line">    &#123;</span><br><span class="line">        System.out.print(&quot;获得CPU时间--&gt;&quot;);</span><br><span class="line">        if(stateName.equals(&quot;就绪状态&quot;))</span><br><span class="line">        &#123;</span><br><span class="line">            hj.setState(new Running());</span><br><span class="line">        &#125;</span><br><span class="line">        else</span><br><span class="line">        &#123;</span><br><span class="line">            System.out.println(&quot;当前线程不是就绪状态，不能获取CPU.&quot;);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;   </span><br><span class="line">&#125;</span><br><span class="line">&#x2F;&#x2F;具体状态类：运行状态</span><br><span class="line">class Running extends ThreadState</span><br><span class="line">&#123;</span><br><span class="line">    public Running()</span><br><span class="line">    &#123;       </span><br><span class="line">        stateName&#x3D;&quot;运行状态&quot;;</span><br><span class="line">        System.out.println(&quot;当前线程处于：运行状态.&quot;);   </span><br><span class="line">    &#125;</span><br><span class="line">    public void suspend(ThreadContext hj)</span><br><span class="line">    &#123;</span><br><span class="line">        System.out.print(&quot;调用suspend()方法--&gt;&quot;);</span><br><span class="line">        if(stateName.equals(&quot;运行状态&quot;))</span><br><span class="line">        &#123;</span><br><span class="line">            hj.setState(new Blocked());</span><br><span class="line">        &#125;</span><br><span class="line">        else</span><br><span class="line">        &#123;</span><br><span class="line">            System.out.println(&quot;当前线程不是运行状态，不能调用suspend()方法.&quot;);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    public void stop(ThreadContext hj)</span><br><span class="line">    &#123;</span><br><span class="line">        System.out.print(&quot;调用stop()方法--&gt;&quot;);</span><br><span class="line">        if(stateName.equals(&quot;运行状态&quot;))</span><br><span class="line">        &#123;</span><br><span class="line">            hj.setState(new Dead());</span><br><span class="line">        &#125;</span><br><span class="line">        else</span><br><span class="line">        &#123;</span><br><span class="line">            System.out.println(&quot;当前线程不是运行状态，不能调用stop()方法.&quot;);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line">&#x2F;&#x2F;具体状态类：阻塞状态</span><br><span class="line">class Blocked extends ThreadState</span><br><span class="line">&#123;</span><br><span class="line">    public Blocked()</span><br><span class="line">    &#123;       </span><br><span class="line">        stateName&#x3D;&quot;阻塞状态&quot;;</span><br><span class="line">        System.out.println(&quot;当前线程处于：阻塞状态.&quot;);   </span><br><span class="line">    &#125;</span><br><span class="line">    public void resume(ThreadContext hj)</span><br><span class="line">    &#123;</span><br><span class="line">        System.out.print(&quot;调用resume()方法--&gt;&quot;);</span><br><span class="line">        if(stateName.equals(&quot;阻塞状态&quot;))</span><br><span class="line">        &#123;</span><br><span class="line">            hj.setState(new Runnable());</span><br><span class="line">        &#125;</span><br><span class="line">        else</span><br><span class="line">        &#123;</span><br><span class="line">            System.out.println(&quot;当前线程不是阻塞状态，不能调用resume()方法.&quot;);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;   </span><br><span class="line">&#125;</span><br><span class="line">&#x2F;&#x2F;具体状态类：死亡状态</span><br><span class="line">class Dead extends ThreadState</span><br><span class="line">&#123;</span><br><span class="line">    public Dead()</span><br><span class="line">    &#123;</span><br><span class="line">        stateName&#x3D;&quot;死亡状态&quot;;</span><br><span class="line">        System.out.println(&quot;当前线程处于：死亡状态.&quot;);   </span><br><span class="line">    &#125;   </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>


<p>程序运行结果如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">当前线程处于：新建状态.</span><br><span class="line">调用start()方法--&gt;当前线程处于：就绪状态.</span><br><span class="line">获得CPU时间--&gt;当前线程处于：运行状态.</span><br><span class="line">调用suspend()方法--&gt;当前线程处于：阻塞状态.</span><br><span class="line">调用resume()方法--&gt;当前线程处于：就绪状态.</span><br><span class="line">获得CPU时间--&gt;当前线程处于：运行状态.</span><br><span class="line">调用stop()方法--&gt;当前线程处于：死亡状态.</span><br></pre></td></tr></table></figure>

<h2 id="状态模式的应用场景"><a href="#状态模式的应用场景" class="headerlink" title="状态模式的应用场景"></a>状态模式的应用场景</h2><p>通常在以下情况下可以考虑使用状态模式。</p>
<ul>
<li>当一个对象的行为取决于它的状态，并且它必须在运行时根据状态改变它的行为时，就可以考虑使用状态模式。</li>
<li>一个操作中含有庞大的分支结构，并且这些分支决定于对象的状态时。<h2 id="状态模式的扩展"><a href="#状态模式的扩展" class="headerlink" title="状态模式的扩展"></a>状态模式的扩展</h2>在有些情况下，可能有多个环境对象需要共享一组状态，这时需要引入享元模式，将这些具体状态对象放在集合中供程序共享，其结构图如图 5 所示。</li>
</ul>
<p><img src="http://c.biancheng.net/uploads/allimg/181116/3-1Q116154539147.gif" alt="共享状态模式的结构图"><br>图5 共享状态模式的结构图</p>
<p>分析：共享状态模式的不同之处是在环境类中增加了一个 HashMap 来保存相关状态，当需要某种状态时可以从中获取，其程序代码如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br></pre></td><td class="code"><pre><span class="line">package state;</span><br><span class="line">import java.util.HashMap;</span><br><span class="line">public class FlyweightStatePattern</span><br><span class="line">&#123;</span><br><span class="line">    public static void main(String[] args)</span><br><span class="line">    &#123;</span><br><span class="line">        ShareContext context&#x3D;new ShareContext(); &#x2F;&#x2F;创建环境       </span><br><span class="line">        context.Handle(); &#x2F;&#x2F;处理请求</span><br><span class="line">        context.Handle();</span><br><span class="line">        context.Handle();</span><br><span class="line">        context.Handle();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line">&#x2F;&#x2F;环境类</span><br><span class="line">class ShareContext</span><br><span class="line">&#123;</span><br><span class="line">    private ShareState state;</span><br><span class="line">    private HashMap&lt;String, ShareState&gt; stateSet&#x3D;new HashMap&lt;String, ShareState&gt;();</span><br><span class="line">    public ShareContext()</span><br><span class="line">    &#123;</span><br><span class="line">        state&#x3D;new ConcreteState1();</span><br><span class="line">        stateSet.put(&quot;1&quot;, state);</span><br><span class="line">        state&#x3D;new ConcreteState2();</span><br><span class="line">        stateSet.put(&quot;2&quot;, state);</span><br><span class="line">        state&#x3D;getState(&quot;1&quot;);</span><br><span class="line">    &#125;</span><br><span class="line">    &#x2F;&#x2F;设置新状态</span><br><span class="line">    public void setState(ShareState state)</span><br><span class="line">    &#123;</span><br><span class="line">        this.state&#x3D;state;</span><br><span class="line">    &#125;</span><br><span class="line">    &#x2F;&#x2F;读取状态</span><br><span class="line">    public ShareState getState(String key)</span><br><span class="line">    &#123;</span><br><span class="line">        ShareState s&#x3D;(ShareState)stateSet.get(key);</span><br><span class="line">        return s;</span><br><span class="line">    &#125;</span><br><span class="line">    &#x2F;&#x2F;对请求做处理</span><br><span class="line">    public void Handle()</span><br><span class="line">    &#123;</span><br><span class="line">        state.Handle(this);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line">&#x2F;&#x2F;抽象状态类</span><br><span class="line">abstract class ShareState</span><br><span class="line">&#123;</span><br><span class="line">    public abstract void Handle(ShareContext context);</span><br><span class="line">&#125;</span><br><span class="line">&#x2F;&#x2F;具体状态1类</span><br><span class="line">class ConcreteState1 extends ShareState</span><br><span class="line">&#123;</span><br><span class="line">    public void Handle(ShareContext context)</span><br><span class="line">    &#123;</span><br><span class="line">        System.out.println(&quot;当前状态是： 状态1&quot;);</span><br><span class="line">        context.setState(context.getState(&quot;2&quot;));</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line">&#x2F;&#x2F;具体状态2类</span><br><span class="line">class ConcreteState2 extends ShareState</span><br><span class="line">&#123;</span><br><span class="line">    public void Handle(ShareContext context)</span><br><span class="line">    &#123;</span><br><span class="line">        System.out.println(&quot;当前状态是： 状态2&quot;);</span><br><span class="line">        context.setState(context.getState(&quot;1&quot;));</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>


<p>程序运行结果如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">当前状态是： 状态1</span><br><span class="line">当前状态是： 状态2</span><br><span class="line">当前状态是： 状态1</span><br><span class="line">当前状态是： 状态2</span><br></pre></td></tr></table></figure>
    </div>

    
    
    

      <footer class="post-footer">

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/myblogs/2020/01/17/%E3%80%9032%E3%80%91%E4%B8%AD%E4%BB%8B%E8%80%85%E6%A8%A1%E5%BC%8F%EF%BC%88%E8%AF%A6%E8%A7%A3%E7%89%88%EF%BC%89/" rel="prev" title="【32】中介者模式（详解版）">
      <i class="fa fa-chevron-left"></i> 【32】中介者模式（详解版）
    </a></div>
      <div class="post-nav-item">
    <a href="/myblogs/2020/01/17/%E3%80%902%E3%80%91GoF%20%E7%9A%84%2023%20%E7%A7%8D%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F%E7%9A%84%E5%88%86%E7%B1%BB%E5%92%8C%E5%8A%9F%E8%83%BD/" rel="next" title="【2】GoF 的 23 种设计模式的分类和功能">
      【2】GoF 的 23 种设计模式的分类和功能 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  

  </div>


          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let activeClass = CONFIG.comments.activeClass;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#【30】状态模式（详解版）"><span class="nav-number">1.</span> <span class="nav-text">【30】状态模式（详解版）</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#状态模式的定义与特点"><span class="nav-number">2.</span> <span class="nav-text">状态模式的定义与特点</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#状态模式的结构与实现"><span class="nav-number">3.</span> <span class="nav-text">状态模式的结构与实现</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#1-模式的结构"><span class="nav-number">3.0.1.</span> <span class="nav-text">1. 模式的结构</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-模式的实现"><span class="nav-number">3.0.2.</span> <span class="nav-text">2. 模式的实现</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#状态模式的应用实例"><span class="nav-number">4.</span> <span class="nav-text">状态模式的应用实例</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#状态模式的应用场景"><span class="nav-number">5.</span> <span class="nav-text">状态模式的应用场景</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#状态模式的扩展"><span class="nav-number">6.</span> <span class="nav-text">状态模式的扩展</span></a></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="H.m"
      src="http://img.hao661.com/zt.hao661.com/uploads/allimg/141006/0644042451-0.jpg">
  <p class="site-author-name" itemprop="name">H.m</p>
  <div class="site-description" itemprop="description">欢迎您的到来！</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/myblogs/archives/">
        
          <span class="site-state-item-count">42</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/myblogs/categories/">
          
        <span class="site-state-item-count">3</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://github.com/hackmgod" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;hackmgod" rel="noopener" target="_blank"><i class="fa fa-fw fa-github"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="/myblogs/hackmgod@foxmail.com" title="E-Mail → hackmgod@foxmail.com"><i class="fa fa-fw fa-envelope"></i>E-Mail</a>
      </span>
      <span class="links-of-author-item">
        <a href="/myblogs/975643993@qq.com" title="QQ → 975643993@qq.com"><i class="fa fa-fw fa-qq"></i>QQ</a>
      </span>
      <span class="links-of-author-item">
        <a href="/myblogs/atom.xml" title="RSS → &#x2F;atom.xml"><i class="fa fa-fw fa-rss"></i>RSS</a>
      </span>
  </div>


  <div class="links-of-blogroll motion-element">
    <div class="links-of-blogroll-title">
      <i class="fa fa-fw fa-link"></i>
      友情链接
    </div>
    <ul class="links-of-blogroll-list">
        <li class="links-of-blogroll-item">
          <a href="https://www.baidu.com/" title="https:&#x2F;&#x2F;www.baidu.com&#x2F;" rel="noopener" target="_blank">百度</a>
        </li>
        <li class="links-of-blogroll-item">
          <a href="https://www.iqiyi.com/" title="https:&#x2F;&#x2F;www.iqiyi.com&#x2F;" rel="noopener" target="_blank">爱奇艺</a>
        </li>
    </ul>
  </div>

      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        <!-- 用下面的符号注释，注释代码用下面括号括起来 -->
<!-- -->

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">H.m</span>
</div>


<!--
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> 强力驱动 v4.2.0
  </div>
  <span class="post-meta-divider">|</span>
  <div class="theme-info">主题 – <a href="https://theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Gemini</a> v7.7.0
  </div> -->

<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>

<div class="powered-by">
  <i class="fa fa-user-md"></i>
  <span id="busuanzi_container_site_pv">
    本站访问量:<span id="busuanzi_value_site_pv"></span>次
  </span>
  <span class="post-meta-divider">|</span>
  <span id="busuanzi_container_site_uv">
    本站总访客量：<span id="busuanzi_value_site_uv"></span>人
  </span>
</div>





        








      </div>
    </footer>
  </div>

  
  <script src="/myblogs/lib/anime.min.js"></script>
  <script src="/myblogs/lib/velocity/velocity.min.js"></script>
  <script src="/myblogs/lib/velocity/velocity.ui.min.js"></script>

<script src="/myblogs/js/utils.js"></script>

<script src="/myblogs/js/motion.js"></script>


<script src="/myblogs/js/schemes/pisces.js"></script>


<script src="/myblogs/js/next-boot.js"></script>




  




  
<script src="/myblogs/js/local-search.js"></script>













  

  

</body>
</html>


<a href="https://github.com/hackmgod" target="_blank" rel="noopener" class="github-corner" aria-label="View source on GitHub"><svg width="80" height="80" viewBox="0 0 250 250" style="fill:#151513; color:#fff; position: absolute; top: 0; border: 0; right: 0;" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a><style>.github-corner:hover .octo-arm{animation:octocat-wave 560ms ease-in-out}@keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}@media (max-width:500px){.github-corner:hover .octo-arm{animation:none}.github-corner .octo-arm{animation:octocat-wave 560ms ease-in-out}}</style>


<!-- 动态背景 -->
<script type="text/javascript" src="//cdn.bootcss.com/canvas-nest.js/1.0.0/canvas-nest.min.js"></script>
<!-- 页面点击小红心 -->
<script type="text/javascript" src="/js/src/clicklove.js"></script>